package com.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.base.BaseController;
import com.conf.StringRedisUtils;
import com.model.auto.GaoKaoConfig;
import com.model.auto.MembershipCard;
import com.model.auto.Student;
import com.model.auto.SysUser;
import com.model.auto.vo.bindingVo;
import com.service.IGaoKaoConfigService;
import com.service.IMembershipCardService;
import com.service.IStudentService;
import com.service.ISysUserService;
import com.util.Ali.SendSms;
import com.util.DateUtils;
import com.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理
 *
 * @author astupidcoder
 * @since 2022-09-14
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IMembershipCardService membershipCardService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    protected RestTemplate restTemplate;
    @Autowired
    private StringRedisUtils stringRedisUtils;
    @Autowired
    private IGaoKaoConfigService gaoKaoConfigService;

    //发送学生注册验证码
    @PostMapping("/syan")
    public R syan(String phone) {
        //调用业务方法
        int login = sysUserService.login(phone);
        //进行判断
        if (login <= 0) {
            String str = "0123456789";
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                char ch = str.charAt(new Random().nextInt(str.length()));
                sb.append(ch);
            }
            String code = sb.toString();
            stringRedisTemplate.opsForValue().set("stu" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("验证码是:" + code);
            try {
                SendSms.sendSms(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok("发送成功！");
        } else {
            return R.error("此号码已被绑定");
        }
    }

    //发送专家注册验证码
    @PostMapping("/zyan")
    public R zyan(String phone) {
        //调用业务方法
        int login = Math.toIntExact(sysUserService.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserType, 3)
                .eq(SysUser::getPhone,phone)
        ));
        System.out.println("这是login"+login);
        //进行判断
        if (login <= 0) {
            String str = "0123456789";
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                char ch = str.charAt(new Random().nextInt(str.length()));
                sb.append(ch);
            }
            String code = sb.toString();
            stringRedisTemplate.opsForValue().set("zj" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("验证码是:" + code);
            try {
                SendSms.sendSms(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok("发送成功！");
        } else {
            return R.error("此号码已被绑定");
        }
    }

    /**
     * 获取卡类型
     * @param cardCode
     * @return
     */
    @GetMapping("/getUserLevel")
    public R getUserLevel(String cardCode) {
        if (StringUtils.hasText(cardCode)) {
            List<MembershipCard> list = membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                    .eq(StringUtils.hasText(cardCode), MembershipCard::getCardNumber, cardCode)
                    .eq(MembershipCard::getState, 1)
                    .eq(MembershipCard::getType, 2)
                    .in(MembershipCard::getLevel, 1, 2)
            );
            if (list.size() > 0) {
                if (list.get(0).getLevel() == 1) {
                    return R.ok("请求成功", "会员卡");
                } else {
                    return R.ok("请求成功", "体验卡");
                }
            }
        }
        return R.ok("请求成功", "");
    }

    /**
     * 处理学生注册请求
     * @param sysUser
     * @param phone
     * @param code
     * @param codepwd
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody SysUser sysUser, String phone, String code, String codepwd) {

        if(!StringUtils.hasText(code)){
            code = sysUser.getCode();
        }
        if(!StringUtils.hasText(codepwd)){
            codepwd = sysUser.getCodepwd();
        }

        //内置万能验证码
        String wCode = DateUtils.format(new Date(), DateUtils.DAY_PATTERN);

        String val = stringRedisTemplate.opsForValue().get("stu" + sysUser.getPhone());
        if ((StringUtils.hasText(val) && val.equals(code)) || wCode.equals(code)) {
            List<MembershipCard> list = membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                    .eq(StringUtils.hasText(sysUser.getCardCode()), MembershipCard::getCardNumber, sysUser.getCardCode())
                    .eq(StringUtils.hasText(codepwd), MembershipCard::getPassword, codepwd)
                    .eq(MembershipCard::getState, 1)
                    .eq(MembershipCard::getType, 2)
                    .in(MembershipCard::getLevel, 1, 2)
            );
            if (list.size() <= 0) {
                return R.error("请输入正确的智能卡号和初始密码！");
            } else {
                List<SysUser> repeat = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getCardCode, sysUser.getCardCode()));
                if (repeat.size() <= 0) {
                    MembershipCard membershipCard = list.get(0);
                    if (membershipCard.getActivate() == 2) {
                        return R.error("该智能卡号已激活！");
                    }
                    List<SysUser> phoneUser = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                            .eq(SysUser::getPhone, sysUser.getPhone())
                            .eq(SysUser::getUserType, 4)
                    );
                    Boolean stuUpdate = false;
                    if (membershipCard.getLevel() == 1) {
                        //如果是会员卡
                        if (phoneUser.size() > 0) {
                            if (phoneUser.get(0).getUserLevel() == 1) {
                                return R.error("该手机号码已注册！");
                            } else {
                                sysUser.setUserId(phoneUser.get(0).getUserId());
                                stuUpdate = true;
                            }
                        }
                    } else {
                        if (phoneUser.size() > 0) {
                            return R.error("该手机号码已注册！");
                        }
                    }
                    sysUser.setUserType(4);
                    sysUser.setUserLevel(membershipCard.getLevel());
                    String year = sysUser.getYear();
                    year = year.substring(0, 4);
                    sysUser.setYear(year);
                    Date date = new Date();
                    Calendar time = Calendar.getInstance();
                    time.setTime(date);
                    time.set(Calendar.YEAR, Integer.parseInt(year));
                    time.set(Calendar.MONTH, 7);
                    time.set(Calendar.DATE, 31);
                    Date kill = time.getTime();
                    sysUser.setCreateDate(LocalDateTime.now());

                    if (membershipCard.getLevel() == 1) {
                        //如果是会员卡
                        sysUser.setExpirationDate(kill.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                    } else if (membershipCard.getLevel() == 2) {
                        //如果是体验卡  系统根据注册时间后延90天计算截止日期
                        sysUser.setExpirationDate(LocalDate.now().plusDays(90));
                    }
                    sysUser.setRemarks(membershipCard.getRemark());

                    //调用底层方法
                    boolean i = sysUserService.saveOrUpdate(sysUser);
                    //进行判断
                    if (i = true) {
                        MembershipCard card = new MembershipCard();
                        card.setId(membershipCard.getId());
                        card.setActivate(2);
                        card.setActivationTime(date);
                        if (membershipCard.getLevel() == 1) {
                            card.setExpirationTime(kill);
                        }
                        sysUser.setUserLevel(membershipCard.getLevel());
                        membershipCardService.updateById(card);
                        Student stu = new Student();
                        if (stuUpdate) {
                            stu = studentService.selectByUserId(sysUser.getUserId());
                            if (Objects.isNull(stu)) {
                                stu = new Student();
                            }
                        }
                        stu.setName(sysUser.getNickName());
                        stu.setUserId(sysUser.getUserId().intValue());
                        System.out.println("返回的id" + sysUser.getUserId());
                        stu.setMajor(sysUser.getMajorType());
                        stu.setSchool(sysUser.getSchool());
                        stu.setOther(sysUser.getYear());
                        stu.setSubject1(sysUser.getSubject1());
                        stu.setSubject2(sysUser.getSubject2());

                        //判断高考年份的7月31号距今小于1年，禁止修改选科
                        Long day = (kill.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);
                        if (day <= 365) {
                            stu.setDisabledMajor(true);
                        }
                        boolean stuOk = studentService.saveOrUpdate(stu);
                        return R.ok("注册成功！");
                    } else {
                        return R.error("注册失败！");
                    }

                } else {
                    return R.error("该卡号已被绑定！");
                }
            }
        } else {
            return R.error("验证码错误！");
        }
    }

    //处理专家注册请求
    @PostMapping("/registers")
    public R register(@RequestBody SysUser sysUser, String code, String codepwd) {
        List<SysUser> user = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(StringUtils.hasText(sysUser.getPhone()), SysUser::getPhone, sysUser.getPhone())
                .eq(SysUser::getUserType, 3)
        );
        if (user.size() <= 0) {
            //内置万能验证码
            String wCode = DateUtils.format(new Date(), DateUtils.DAY_PATTERN);

            String val = stringRedisTemplate.opsForValue().get("zj" + sysUser.getPhone());
            if ((StringUtils.hasText(val) && val.equals(code)) || wCode.equals(code)) {
                List<MembershipCard> list = membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                        .eq(StringUtils.hasText(sysUser.getCardCode()), MembershipCard::getCardNumber, sysUser.getCardCode())
                        .eq(MembershipCard::getState, 1)
                        .eq(MembershipCard::getType, 1)
                        .in(MembershipCard::getLevel, 3,4,5)
                );
                if (list.size() <= 0) {
                    return R.error("请输入正确的卡号！");
                } else {
                    List<SysUser> repeat = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                            .eq(SysUser::getCardCode, sysUser.getCardCode()));
                    List<MembershipCard> membershipCards = membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                            .eq(MembershipCard::getActivate, 1)
                            .eq(StringUtils.hasText(sysUser.getCardCode()), MembershipCard::getCardNumber, sysUser.getCardCode())
                            .eq(MembershipCard::getState, 1)
                            .eq(MembershipCard::getType, 1)
                            .in(MembershipCard::getLevel, 3,4,5)
                    );
                    System.out.println("这是查到用户" + repeat.size() + "这是查到卡" + membershipCards.size());
                    if (repeat.size() <= 0 && membershipCards.size() > 0) {
                        List<MembershipCard> list1 = membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                                .eq(StringUtils.hasText(sysUser.getCardCode()), MembershipCard::getCardNumber, sysUser.getCardCode())
                                .eq(StringUtils.hasText(codepwd), MembershipCard::getPassword, codepwd));
                        if (list1.size() <= 0) {
                            return R.error("密码错误！");
                        } else {
                            if(list1.get(0).getActivate() == 2){
                                return R.error("该智能卡号已激活！");
                            }
                            sysUser.setUserType(3);
                            sysUser.setCreateDate(LocalDateTime.now());
                            sysUser.setUserLevel(list1.get(0).getLevel());
                            sysUser.setCardCode(list1.get(0).getCardNumber());
                            sysUser.setExpirationDate(list1.get(0).getExpirationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                            sysUser.setRemarks(list1.get(0).getRemark());
                            //调用底层方法
                            boolean i = sysUserService.save(sysUser);
                            //进行判断
                            if (i = true) {
                                Date date = new Date();
                                MembershipCard card = new MembershipCard();
                                card.setId(list1.get(0).getId());
                                card.setActivate(2);
                                card.setActivationTime(date);
                                membershipCardService.updateById(card);
                                return R.ok("注册成功！");
                            } else {
                                return R.error("注册失败！");
                            }
                        }
                    } else {
                        return R.error("该卡号已被绑定！");
                    }

                }
            } else {
                return R.error("验证码错误！");
            }
        } else {
            return R.error("该号码已被注册！");
        }

    }


    //发送登录验证码
    @PostMapping("/yan")
    public R yan(String phone) {
        //调用底层
        //调用业务方法
        int login = sysUserService.login(phone);
        System.out.println(login);
        //进行判断
        if (login > 0) {
            String str = "0123456789";
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                char ch = str.charAt(new Random().nextInt(str.length()));
                sb.append(ch);
            }
            String code = sb.toString();
            System.out.println("第一次验证码为" + code);
            stringRedisTemplate.opsForValue().set("stu" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("登录验证码为" + code);
            try {
                SendSms.sendSms(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok("发送成功！");
        } else {
            return R.error("此用户不存在，请完成注册后再进行登录。");
        }
    }


    @GetMapping("/getUser")
    public R getUser(String phone) {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhone, phone)
                .eq(SysUser::getUserType, 4)
        );
        return R.ok(sysUser);
    }

    //学生登录
    @PostMapping("/login")
    public R login(String phone, String code, String password, String terminal) {
        if(StringUtils.hasText(password)){
            List<SysUser> user = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                    .eq(SysUser::getUserType, 4)
            );
            if (user.size() > 0) {
                SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getPhone, phone)
                        .eq(StringUtils.hasText(password), SysUser::getPassword, password)
                        .eq(SysUser::getUserType,4)
                );
                if(ObjectUtils.isEmpty(sysUser)){
                    sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                            .eq(SysUser::getPhone, phone+"-已到期")
                            .eq(SysUser::getUserType,4)
                    );
                    if(!ObjectUtils.isEmpty(sysUser)){
                        return R.error("当前该账号已经到期无法登录，请联系工作人员！");
                    }
                    return R.error("用户名或者密码错误！");
                }
                if (Objects.nonNull(sysUser)) {
                    if(sysUser.getStatus()==1){
                        LocalDate nowDate = LocalDate.now();
                        if(Objects.nonNull(sysUser.getExpirationDate()) && nowDate.isAfter(sysUser.getExpirationDate())){
                            return R.error("当前该账号已经到期无法登录，请联系工作人员！");
                        }
                        sysUser.setStuId(studentService.selectIdByUserId(sysUser.getUserId()));
                        sysUser.setDisableFunction(getDisableFunction(sysUser));
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("user", sysUser);
                        if(!StringUtils.hasText(terminal)){
                            terminal = "web";
                        }
                        StpUtil.login(terminal+phone);
                        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
                        map.put("tokenInfo", saTokenInfo);
                        stringRedisUtils.setStringVal(sysUser.getUserId()+terminal, saTokenInfo.getTokenValue());
                        return R.ok(map);
                    }
                    return R.error("当前该账号已被冻结！无法登录！");
                } else {
                    return R.error("密码错误！");
                }
            } else {
                return R.error("此手机号尚未注册或绑定，请先完成相关操作再登陆！");
            }
        }else if(StringUtils.hasText(code)){
            System.out.println("手机号" + phone);
            String redisValue = stringRedisTemplate.opsForValue().get("stu" + phone);
            System.out.println("验证码" + redisValue);
            //内置万能验证码
            String wCode = DateUtils.format(new Date(), DateUtils.DAY_PATTERN);
            if ((StringUtils.hasText(redisValue) && redisValue.equals(code)) || wCode.equals(code)) {
                HashMap<String, Object> map = new HashMap<>();
                SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getPhone, phone)
                        .eq(SysUser::getUserType,4)
                );
                if(ObjectUtils.isEmpty(sysUser)){
                    sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                            .eq(SysUser::getPhone, phone+"-已到期")
                            .eq(SysUser::getUserType,4)
                    );
                    if(!ObjectUtils.isEmpty(sysUser)){
                        return R.error("当前该账号已经到期无法登录，请联系工作人员！");
                    }
                    return R.error("用户名或者密码错误！");
                }
                if(sysUser.getStatus()==1){
                    LocalDate nowDate = LocalDate.now();
                    if(Objects.nonNull(sysUser.getExpirationDate()) && nowDate.isAfter(sysUser.getExpirationDate())){
                        return R.error("当前该账号已经到期无法登录，请联系工作人员！");
                    }
                    sysUser.setStuId(studentService.selectIdByUserId(sysUser.getUserId()));
                    map.put("user", sysUser);
                    if(!StringUtils.hasText(terminal)){
                        terminal = "web";
                    }
                    //传入用户信息
                    StpUtil.login(terminal+phone);
                    //将token返回给前端
                    SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
                    map.put("tokenInfo", saTokenInfo);
                    stringRedisUtils.setStringVal(sysUser.getUserId()+terminal, saTokenInfo.getTokenValue());

                    return R.ok(map);
                }
                return R.error("当前该账号已被冻结！无法登录！");
            }
            return R.error("验证码错误！");
        }else {
            return R.error("登录失败，未输入账户、验证码和密码");
        }
    }

    /**
     * 获取是否禁用 “院校查询”、“定位专业”、“方案设计”模块
     * @param sysUser
     * @return
     */
    private Boolean getDisableFunction(SysUser sysUser) {
        List<GaoKaoConfig> list = gaoKaoConfigService.list();
        if (Objects.nonNull(list)) {
            GaoKaoConfig gaoKaoConfig = list.get(0);
            if (Objects.nonNull(gaoKaoConfig.getStartDate()) && Objects.nonNull(gaoKaoConfig.getEndDate())) {
                if (gaoKaoConfig.getStartDate().isBefore(LocalDateTime.now()) && gaoKaoConfig.getEndDate().isAfter(LocalDateTime.now())) {
                    if (sysUser.getUserLevel() == 2 || sysUser.getYear() != String.valueOf(LocalDateTime.now().getYear())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //专家登录
    @PostMapping("/expertLogin")
    public R expertLogin(String phone, String pwd, String terminal) {
        if (StringUtils.hasText(phone) && StringUtils.hasText(pwd)) {
            List<SysUser> user = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                    .eq(SysUser::getUserType, 3)
            );
            if (user.size() > 0) {
                List<SysUser> sysUsers = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                        .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                        .eq(StringUtils.hasText(pwd), SysUser::getPassword, pwd)
                        .eq(SysUser::getUserType, 3)
                );
                if (sysUsers.size() > 0) {
                    if(sysUsers.get(0).getStatus()==1){
                        LocalDate nowDate = LocalDate.now();
                        if(Objects.nonNull(sysUsers.get(0).getExpirationDate()) && nowDate.isAfter(sysUsers.get(0).getExpirationDate())){
                            return R.error("当前该账号已经到期无法登录，请联系管理员！");
                        }
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("user", sysUsers.get(0));
                        if(!StringUtils.hasText(terminal)){
                            terminal = "web";
                        }
                        StpUtil.login(terminal+phone);
                        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
                        map.put("tokenInfo", saTokenInfo);
                        stringRedisUtils.setStringVal(sysUsers.get(0).getUserId()+terminal, saTokenInfo.getTokenValue());
                        return R.ok(map);
                    }
                    return R.error("当前该账号已被冻结！无法登录！");
                } else {
                    return R.error("密码错误！");
                }
            } else {
                return R.error("此手机号尚未注册或绑定，请先完成相关操作再登陆！");
            }
        } else {
            return R.error("手机号和密码不能为空！");
        }

    }

    //退出登录
    @GetMapping("/logout")
    public R logout(){
        StpUtil.logout();
        return R.ok();
    }




    //专家绑定学生
    @PostMapping("/bindingStu")
    public R bindingStu(@RequestBody bindingVo bindingVo){
        List<MembershipCard> cards=membershipCardService.list(new LambdaQueryWrapper<MembershipCard>()
                .eq(MembershipCard::getCardNumber,bindingVo.getCardNumber())
                .eq(MembershipCard::getLevel,2)
                .eq(MembershipCard::getState,1)
                .eq(MembershipCard::getActivate,2)
        );
        List<SysUser> users=sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getCardCode,bindingVo.getCardNumber())
        );
        if (cards.size()>0&&users.size()>0){
            boolean name=bindingVo.getName().equals(users.get(0).getNickName());
//            System.out.println("密码"+cards.get(0).getPassword()+"输入密码"+bindingVo.getPassword()+password);
            if (name){
                Student student=studentService.getOne(new LambdaQueryWrapper<Student>()
                        .eq(Student::getUserId,users.get(0).getUserId())
                        );
                System.out.println("他的id"+student+users.get(0).getUserId());
                if (student.getCreatedUser()==null){
                    student.setCreatedUser(bindingVo.getUserId());
                    List<Student> stu=studentService.list(new LambdaQueryWrapper<Student>()
                            .eq(student.getCreatedUser()!=null,Student::getCreatedUser,student.getCreatedUser())
                            .orderByDesc(Student::getStuNum).last("limit 1")
                    );
                    if (stu.size()>0){
                        int num=stu.get(0).getStuNum()+1;
                        student.setStuNum(num);
                    }else {
                        student.setStuNum(1);
                    }
                    boolean update=studentService.updateById(student);
                    if (update){
                        return R.ok("绑定成功！");
                    }
                    return R.error("绑定失败！");
                }else{
                    return R.error("该学生已被绑定！");
                }
            }else{
                return R.error("姓名错误！");
            }
         }else{
            return R.error("卡号错误！");
        }
    }



    @PostMapping("/getAccessToken")
    public R getAccessToken(@Param("code") String code) {
        String appid = "wx300c5c2045683f30";
        String secret = "eb7c21badff4ee13b145da6372512f1e";
        String grant_type = "authorization_code";
        //1.构造url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=" + grant_type;
        //2.获取响应结果
        String json = restTemplate.getForObject(url, String.class);
        //3.转化结果
        JSONObject jsonObject = JSONObject.parseObject(json);
        //4.返回结果
        System.out.println("拼接的url" + url);
        System.out.println("返回的结果" + jsonObject);
        return R.ok(json);
    }




    @PostMapping("/wxlogin")
    public R wxlogin(@RequestBody String wxid) {
        List<SysUser> users = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(StringUtils.hasText(wxid), SysUser::getOpenid, wxid));
        HashMap<String, Object> map = new HashMap<>();
        if (users.size() > 0) {
            List user = Collections.singletonList(users.get(0));
            //传入用户信息
            StpUtil.login(users.get(0).getPhone());
            //将token返回给前端
            map.put("tokenInfo", StpUtil.getTokenInfo());
            System.out.println("这个用户" + user);
            map.put("state", 0);
            map.put("user", user);
        } else {
            map.put("state", 1);
        }
        return R.ok(map);
    }


    //专家发送找回密码验证码
    @PostMapping("/zhyz")
    public R zhyz(@RequestBody String phone) {

        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .eq(SysUser::getUserType, 3)
        );
        if (list.size() > 0) {
            String str = "0123456789";
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                char ch = str.charAt(new Random().nextInt(str.length()));
                sb.append(ch);
            }
            String code = sb.toString();
            System.out.println("第一次验证码为" + code);
            stringRedisTemplate.opsForValue().set(phone + "zjzh", code, 5, TimeUnit.MINUTES);
            System.out.println("登录验证码为" + code);
            try {
                SendSms.sendSms(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok("发送成功！");
        } else {
            return R.error("该用户不存在！");
        }
    }


    //学生发送找回密码验证码
    @PostMapping("/stuZhyz")
    public R stuZhyz(@RequestBody String phone) {

        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .eq(SysUser::getUserType, 4)
        );
        if (list.size() > 0) {
            String str = "0123456789";
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++) {
                char ch = str.charAt(new Random().nextInt(str.length()));
                sb.append(ch);
            }
            String code = sb.toString();
            System.out.println("第一次验证码为" + code);
            stringRedisTemplate.opsForValue().set(phone + "zjzh", code, 5, TimeUnit.MINUTES);
            System.out.println("登录验证码为" + code);
            try {
                SendSms.sendSms(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok("发送成功！");
        } else {
            return R.error("该用户不存在！");
        }
    }
    //找回密码验证
    @PostMapping("/yz")
    public R yz(String phone, String code) {
        String redisValue = stringRedisTemplate.opsForValue().get(phone + "zjzh");
        if (StringUtils.hasText(redisValue) && redisValue.equals(code)) {
            return R.ok();
        }
        return R.error("验证码错误！");
    }


    /**
     * 专家修改密码
      * @param phone
     * @param pwd
     * @param code
     * @return
     */
    @PostMapping("/xgmm")
    public R xgmm(String phone, String pwd, String code) {
        String redisValue = stringRedisTemplate.opsForValue().get(phone + "zjzh");
        if (StringUtils.isEmpty(redisValue) || !redisValue.equals(code)) {
            return R.error("验证码错误！");
        }

        boolean up = sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .eq(SysUser::getUserType, 3)
                .set(SysUser::getPassword, pwd));
        if (up) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 学生修改密码
     * @param phone
     * @param pwd
     * @param code
     * @return
     */
    @PostMapping("/stuUpdatePassword")
    public R stuUpdatePassword(String phone, String pwd, String code) {
        String redisValue = stringRedisTemplate.opsForValue().get(phone + "zjzh");
        if (StringUtils.isEmpty(redisValue) || !redisValue.equals(code)) {
            return R.error("验证码错误！");
        }

        boolean up = sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                .eq(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .eq(SysUser::getUserType, 4)
                .set(SysUser::getPassword, pwd));
        if (up) {
            return R.ok();
        } else {
            return R.error();
        }
    }

}
